//
//  SinaClient.m
//
//  Created by Northwan on 27/5/15.
//  Copyright (c) 2014  All rights reserved.
//

#import "SinaClient.h"
#import "WeChatUserinfoRes.h"
@interface SinaClient()
{
    WBAuthorizeRequest *request;
    BOOL    isNeedAvatar;
    BOOL    isSendWeibo;
}
@property (strong,nonatomic) NSString *sendText;
@property (strong,nonatomic) UIImage  *sendImage;
@end

@implementation SinaClient
- (id)initSinaClient
{
    if (self=[super init]) {
        request = [WBAuthorizeRequest request];
        request.redirectURI = kSinaRedirectURL;
        request.scope = @"all";
        isNeedAvatar = NO;
        isSendWeibo = NO;

        self.wbtoken =  [DefaultsHelper stringForKey:kSinaLoginAccessToken];
    }
    return self;
}

+(SinaClient *)ShareSinaClient
{
    static SinaClient *singleClient;
    static dispatch_once_t pred;
    dispatch_once(&pred, ^{
        singleClient = [[self alloc] initSinaClient];
    });
    return singleClient;
}

- (void)successBindWeibo:(WBAuthorizeResponse *)response
{
    self.wbtoken = [response accessToken];
    if (ISBLANK(self.wbtoken)) {
        ShowTips(@"绑定新浪微博失败");
        return;
    }
    [DefaultsHelper setObject:self.wbtoken forKey:kSinaLoginAccessToken];
    if (isSendWeibo) {
        [self sendWeiBo:self.sendText WithImage:self.sendImage];
        return;
    }

    NSString *str = @"https://api.weibo.com/2/users/show.json";
    [WBHttpRequest requestWithAccessToken:self.wbtoken
                                      url:str
                               httpMethod:@"GET"
                                   params:@{@"uid":[response userID]}
                                 delegate:self
                                  withTag:nil];
}

///通过微博绑定获取头像
- (void)weiboGetAvatar;
{
    isSendWeibo = NO;
    isNeedAvatar = YES;
    [self weiboLogin];
}

///进行微博绑定,上传相关到服务器
- (void)weiboBind
{
    isSendWeibo = NO;
    [self weiboLogin];
}

///发送微博
- (void)sendWeiBo:(NSString *)text WithImage:(UIImage *)image
{
    isSendWeibo = YES;
    if ([WeiboSDK isWeiboAppInstalled]) {
        WBMessageObject *message = [WBMessageObject message];
        
        if (!ISBLANK(text))
        {
            message.text = text;
        }
        if (image)
        {
            WBImageObject *imageObj = [WBImageObject object];
            imageObj.imageData = UIImageJPEGRepresentation(image, 0.8);
            message.imageObject = imageObj;
        }
        WBSendMessageToWeiboRequest *request1 = [WBSendMessageToWeiboRequest requestWithMessage:message];
        [WeiboSDK sendRequest:request1];
    }
    else{
        self.sendImage = image;
        self.sendText = text;
        self.wbtoken = [DefaultsHelper stringForKey:kSinaLoginAccessToken];
        if (ISBLANK(self.wbtoken)) {
            [self weiboBind];
            return;
        }
        if(image){ ///图文
            
            NSString *str = @"https://upload.api.weibo.com/2/statuses/upload.json";
            [WBHttpRequest requestWithAccessToken:self.wbtoken
                                              url:str
                                       httpMethod:@"POST"
                                           params:@{@"pic":UIImageJPEGRepresentation(image, 0.8),@"status":[text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]}
                                         delegate:self
                                          withTag:nil];
        }
        else{ ///文字
            NSString *str = @"https://api.weibo.com/2/statuses/update.json";
            [WBHttpRequest requestWithAccessToken:self.wbtoken
                                              url:str
                                       httpMethod:@"POST"
                                           params:@{@"status":[text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]}
                                         delegate:self
                                          withTag:nil];
        }
        
    }
    
}

- (void)sendWeiBo:(NSString *)title description:(NSString *)description WithImgUrl:(NSString *)imgUrl webpageUrl:(NSString *)webpageUrl{
    isSendWeibo = YES;
    
    NSString *text = [NSString stringWithFormat:@"%@%@",description, webpageUrl];
    if (text.length > 100) {
        if (webpageUrl.length > 100) {
            text = description.length > 100 ? [description substringToIndex:100] : description;
        }else if(description.length < webpageUrl.length){
            text = webpageUrl;
        }else{
            text = [NSString stringWithFormat:@"%@%@",[description substringToIndex:(100 - webpageUrl.length)], webpageUrl];
        }
    }
    
    UIImage *img = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:imgUrl];
    
    if ([WeiboSDK isWeiboAppInstalled]) {
        WBMessageObject *message = [WBMessageObject message];
        
        message.text = text;
       
        if (img){
            WBImageObject *imageObj = [WBImageObject object];
            imageObj.imageData = UIImageJPEGRepresentation(img, 0.8);
            message.imageObject = imageObj;
//        }else if (!ISBLANK(webpageUrl) && !ISBLANK(title)) {
//            WBWebpageObject *webpage = [WBWebpageObject object];
//            webpage.objectID = @"identifier1";
//            webpage.title = title;
//            webpage.description = description;
////            webpage.thumbnailData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imgUrl]];
//            if (img) {
//                webpage.thumbnailData = UIImageJPEGRepresentation(img, 0.6);
//            }
//            webpage.webpageUrl = webpageUrl;
//            message.mediaObject = webpage;
        }
        
        WBSendMessageToWeiboRequest *request1 = [WBSendMessageToWeiboRequest requestWithMessage:message];
        [WeiboSDK sendRequest:request1];
    }else{
        [self sendWeiBo:text WithImage:img];
    }
}

- (void)weiboLogin
{
    [WeiboSDK sendRequest:request];
}

- (void)request:(WBHttpRequest *)request didFinishLoadingWithDataResult:(NSData *)data
{
    NSDictionary  *weiboDic = [NSJSONSerialization JSONObjectWithData:data
                                                              options:NSJSONReadingMutableLeaves
                                                                error:nil];
    
    
    if (weiboDic) {
        NSString *name = [weiboDic objectForKey:@"name"];
        NSString *avatar = [weiboDic objectForKey:@"avatar_large"];
        BlockCallWithTwoArg(self.sinaHandler, name, avatar)
    }
    else{
        ShowTips(@"获取新浪微博昵称失败");
        BlockCallWithTwoArg(self.sinaHandler, nil, nil)
    }
    
    
}

- (void)request:(WBHttpRequest *)request didFinishLoadingWithResult:(NSString *)result
{
    if (isSendWeibo) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:[result dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:nil];
        if ([[dict objectForKey:@"error_code"] intValue]!=0) {
            ShowTips(@"发送微博失败");
        }
        else{
            ShowTips(@"发送微博成功");
        }
    }
}

- (void)request:(WBHttpRequest *)request didFailWithError:(NSError *)error;
{
    if (isSendWeibo) {
         ShowTips(@"发送微博失败");
    }
}


@end
